package org.bob.learn.service.impl;

import java.nio.file.Files;
import lombok.extern.slf4j.Slf4j;
import org.bob.learn.service.FileService;
import org.bob.learn.web.model.Result;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.io.File;
import java.nio.file.Paths;

@Slf4j
@Service
public class FileServiceImpl implements FileService {


    @Override
    public Mono<Result<Void>> save(String filePath, FilePart filePart) {
        return filePart.transferTo(Paths.get(filePath + filePart.filename()))
                    .then(Mono.just(Result.Success(Void.class)));
    }

    @Override
    public Mono<Result<File>> read(String filePath) {
        return Mono.fromSupplier(() -> {
            File file = new File(filePath);
            if (file.exists() && file.isFile()) {
                return Result.Success(file);
            } else {
                log.warn("文件[{}]不存在", filePath);
                return Result.Failure("文件不存在");
            }
        });
    }
}
